//
//  HomeViewController.m
//  Weibo
//
//  Created by wpapple on 16/5/30.
//  Copyright © 2016年 wpapple. All rights reserved.
//

#import "HomeViewController.h"
#import "UIBarButtonItem+button.h"
#import "HomeButton.h"
#import "WPMenu.h"
#import "HomeFooterView.h"
#import "HomeViewCell.h"

#define KNumber 20

@interface HomeViewController ()

@property (nonatomic,strong) NSMutableArray *statuses;

@property (nonatomic,strong) UIRefreshControl *refreshControl;

@property (nonatomic,strong) IWStatus *status;
@end

@implementation HomeViewController

-(NSMutableArray *)statuses
{
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *item = [UIBarButtonItem itemWithImage:@"navigationbar_friendsearch" hightImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(itemClicked:)];
    
    self.navigationItem.leftBarButtonItem = item;
    
    //右边的按钮
    UIBarButtonItem *item2 = [UIBarButtonItem itemWithImage:@"navigationbar_pop" hightImageName:@"navigationbar_pop_highlighted" target:self action:@selector(scanClicked)];
    
    self.navigationItem.rightBarButtonItem = item2;
    
    
    //自定义按钮
    HomeButton *btn = [[HomeButton alloc]init];
    
    [btn setTitle:@"首页" forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateSelected];
    
    [btn sizeToFit];

    [btn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.navigationItem.titleView = btn;
    
    //下拉跟新微博
//    BOOL isLogin = [WPAccount isLogin];
//    if (isLogin) {
    
    [self loadStatuses:nil];
    
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc]init];
    self.refreshControl = refreshControl;
    [refreshControl addTarget:self action:@selector(loadStatuses:) forControlEvents:UIControlEventValueChanged];
    
    [self.tableView addSubview:refreshControl];
    
    [self.refreshControl beginRefreshing];
    
    
    //首页布局
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.estimatedRowHeight = 300;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    //去掉分隔线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

}

#pragma mark - 请求微博
-(void)loadStatuses: (UIRefreshControl *)refreshControl
{
    AFHTTPSessionManager * manage = [AFHTTPSessionManager manager];
    
    NSString *url = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    //从沙盒中取
    WPAccount *account = [WPAccount accountFromSandbox];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"access_token"] = account.access_token;
    parameters[@"count"] = @(KNumber);
    
    IWStatus *firststatus = [self.statuses firstObject];
    
    if (firststatus != nil) {
        parameters[@"since_id"] = firststatus.idstr;
    }else
    {
        
    }
    
    [manage GET:url parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"请求成功");
        
        NSArray *newStatus = responseObject[@"statuses"];
        
        //将数组字典转换位模型
        NSArray *models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
        [self.statuses addObjectsFromArray:models];
        
        NSRange range = NSMakeRange(0, models.count);
        
        NSIndexSet *indexset = [NSIndexSet indexSetWithIndexesInRange:range];
        
        [self.statuses insertObjects:models atIndexes:indexset];
        
//        [self.statuses addObjectsFromArray:models];
        
        [self.tableView reloadData];
        
        //结束刷新
        [self.refreshControl endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败");
        [self.refreshControl endRefreshing];
    }];
    
}

#pragma mark - 上拉刷新
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat constoffetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.height;
    
    if (self.tableView.tableFooterView != nil || self.statuses.count == 0) {
        return;
    }
    
    if (scrollView.contentOffset.y >= constoffetY) {
        NSLog(@"下拉");
//        HomeFooterView *footer = [HomeFooterView footerView];
//        [footer stop];
        self.tableView.tableFooterView = [HomeFooterView footerView];
        
        [self loadMoreStatus];
    }
}

//加载更多微博数据
-(void)loadMoreStatus
{
    NSString *url = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    WPAccount *account = [WPAccount accountFromSandbox];
    
    parameters[@"access_token"] = account.access_token;
    parameters[@"count"] = @(KNumber);
    
    IWStatus *lastStatus = [self.statuses lastObject];
    if (lastStatus != nil) {
        parameters[@"max_id"] = @([lastStatus.idstr longLongValue] - 1);
    }else
    {
        
    }
    
     AFHTTPSessionManager *manage = [AFHTTPSessionManager manager];
    
    [manage GET:url parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSArray *newStatus = responseObject[@"statuses"];
        
        //将数组字典转换位模型
        NSArray *models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
        [self.statuses addObjectsFromArray:models];
        
        [self.tableView reloadData];
        
        self.tableView.tableFooterView = nil;

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.tableView.tableFooterView = nil;
    });
    
    
}

-(void)scanClicked
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Scan" bundle:nil];
    
    UIViewController *vc = [sb instantiateInitialViewController];
    
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)titleBtnClick:(HomeButton *)btn
{
    btn.selected = !btn.selected;
    
    UIView *contentView = [[UIView alloc]init];
    
    contentView.frame = CGRectMake(0, 0, 200, 200);
    
    [WPMenu show:contentView withView:btn dismiss:^{
        NSLog(@"sss");
    }];
}

-(void)itemClicked:(UIBarButtonItem *)buttonItem
{
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statuses.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"status";
    
    HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if (cell == nil) {
        
        cell = [[HomeViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identify];
    }
    
    IWStatus *status = self.statuses[indexPath.row];
    
    
    cell.status = status;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}



@end
